//
//  GestionPersonController.m
//  Cabinet
//
//  Created by Florent Montsegur on 21/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GestionPersonController.h"
#import "Vaccination.h"
#import "Vaccin.h"
#import "Person.h"
#import "CabinetDefines.h"
#import "Consultation.h"

@implementation GestionPersonController
@synthesize mManagedObjectContext;
@synthesize mConfSuppPersonneWnd;
@synthesize mConfSuppVaccinationWnd;
@synthesize mConfSuppConsulationWnd;
@synthesize mPersonneInfos;
@synthesize mPersons;
@synthesize mVaccins;
@synthesize mConsultations;
@synthesize mRapportWnd;
@synthesize mRapportTxt;
@synthesize mJumeller;
@synthesize mInformations;
@synthesize mDossierMedWnd;
@synthesize mDossierMedTxt;

- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}


- (NSString*)windowNibName
{    
	return @"GestionPerson";
}


- (void)windowDidLoad
{
    [super windowDidLoad];
    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}

- (IBAction)supprimerPersonneAction:sender
{
    Person * p =[[self mPersons] selection];
    if(p == nil)
        return;
     
    [[self mPersons] remove:[[self mPersons] selection]];
    [[self mConfSuppPersonneWnd] performClose:nil];
}

- (IBAction)supprimerVaccinationAction:sender{
    
    Vaccination * v =[[self mVaccins] selection];
    if(v == nil)
        return;
    
    [[self mVaccins] remove:[[self mVaccins] selection]];
    
    [[self mConfSuppVaccinationWnd] performClose:nil];
}

- (IBAction)supprimerConsultationAction:sender{
    
    Consultation * cons =[[self mConsultations] selection];
    if(cons == nil)
        return;
    
    [[self mConsultations] remove:[[self mConsultations] selection]];
    
    [[self mConfSuppConsulationWnd] performClose:nil];
}

- (IBAction)printRapportAction:sender
{    
    NSArray *peronnes = [[self mPersons] selectedObjects];
    if( [peronnes count] <=0 )
        return;
    
    Person * p = [peronnes objectAtIndex:0];
    if(p == nil)
        return;
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ %@\n", [p Prenom], [p Nom]]];
    //NSInteger taille = [str length] - 1;
    //[str addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"Arial-Bold" size:11] range:NSMakeRange(0, taille)];
    
    NSFont *font = [NSFont fontWithName:@"Arial" size:11];
    
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString:str];
    
    if ( ([p Sexe] == [NSNumber numberWithInt:Mademoiselle]) || ([p Sexe] == [NSNumber numberWithInt:Madame]) )
    {
        str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"Née le %@\n\n", [[p Naissance] descriptionWithCalendarFormat:@"%d/%m/%Y" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]] ];
    }
    else
    {
        str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"Né le %@\n\n", [[p Naissance] descriptionWithCalendarFormat:@"%d/%m/%Y" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]] ];
    }
    
    [str addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [str length])];
    
    [text appendAttributedString:str];
    
    
    [self ajouterVaccinsRapport:text font:font person:p];
    
    [[[self mRapportTxt] textStorage] setAttributedString: text];
  
    [[self mRapportWnd] makeKeyAndOrderFront:sender];
}


- (IBAction)printDossierMedAction:sender{
    NSArray *peronnes = [[self mPersons] selectedObjects];
    if( [peronnes count] <=0 )
        return;
    
    Person * p = [peronnes objectAtIndex:0];
    if(p == nil)
        return;
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"Dossier médical de %@ %@ \nNé le %@\n\n", [p Prenom], [p Nom], [[p Naissance] descriptionWithCalendarFormat:@"%d/%m/%Y" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]] ];
    
    NSFont *fontEnTete = [NSFont fontWithName:@"Arial" size:12];
    
    [str addAttribute:NSFontAttributeName value:fontEnTete range:NSMakeRange(0, [str length])];
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString:str];
    
    NSFont *fontTitre = [NSFont fontWithName:@"Arial" size:12];
    NSFont *fontCorp = [NSFont fontWithName:@"Arial" size:11];
    
    // Informations
    [self ajouterTitreRapport:text font:fontTitre titre:[NSString stringWithFormat:@"Informations\n\n"]];
    [self ajouterInformationsRapport:text font:fontCorp person:p];
    
    // Vaccins
    [self ajouterTitreRapport:text font:fontTitre titre:[NSString stringWithFormat:@"\nVaccins\n"]];
    [self ajouterVaccinsRapport:text font:fontCorp person:p];
    
    // Actes
    [self ajouterTitreRapport:text font:fontTitre titre:[NSString stringWithFormat:@"\nHistorique des actes\n\n"]];
    [self ajouterActesRapport:text font:fontCorp person:p];
    
    
    [[[self mDossierMedTxt] textStorage] setAttributedString: text];
    [[self mDossierMedWnd] makeKeyAndOrderFront:sender];
}


-(void) ajouterTitreRapport:(NSMutableAttributedString *)aText font:(NSFont *)aFont titre:(NSString *)aTitre{
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:aTitre];
    [str addAttribute: NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSSingleUnderlineStyle] range:NSMakeRange(0, [str length])];
    [str addAttribute:NSFontAttributeName value:aFont range:NSMakeRange(0, [str length])];
    [aText appendAttributedString:str];
}

-(void) ajouterInformationsRapport:(NSMutableAttributedString *)aText font:(NSFont *)aFont person:(Person *)pPerson{
    
    NSMutableAttributedString *str = nil;
    if( [[pPerson Commentaires] length] <= 0 ){
        str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"\n"]];
    }
    else{
        str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n", [pPerson Commentaires]] ];
    }
    [str addAttribute:NSFontAttributeName value:aFont range:NSMakeRange(0, [str length])];
    [aText appendAttributedString:str];
}

-(void) ajouterVaccinsRapport:(NSMutableAttributedString *)aText font:(NSFont *)aFont person:(Person *)pPerson{
    
    NSArray * vaccins = [[pPerson Vaccinations] allObjects];
    NSArray * sortedVaccins = [vaccins sortedArrayUsingDescriptors:[NSArray arrayWithObjects:
                                                                    [[NSSortDescriptor alloc] initWithKey:@"Vaccin.Type" ascending:YES],
                                                                    [[NSSortDescriptor alloc] initWithKey:@"Date" ascending:NO],
                                                                    nil]];
    NSNumber *t = [NSNumber numberWithInt:-1];
    for(int i = 0; i<[sortedVaccins count]; i++)
    {
        Vaccination *v = [sortedVaccins objectAtIndex:i];
        if(v != nil)
        {
            if([[v Vaccin] Type] != t)
            {
                [aText appendAttributedString:[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"\n"]]];
                t = [[v Vaccin] Type];
            }
            
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\t\t%-15s\t%-20s\t%@\n",
                                                                                                 [[v Date] descriptionWithCalendarFormat:@"%d/%m/%Y" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]],
                                                                                                 [[v Lot] UTF8String],
                                                                                                 [[v Rang] UTF8String],
                                                                                                 [[v Vaccin] Nom] ]];
            
            [str addAttribute:NSFontAttributeName value:aFont range:NSMakeRange(0, [str length])];
            [aText appendAttributedString:str];
        }
    }
}


-(void) ajouterActesRapport:(NSMutableAttributedString *)aText font:(NSFont *)aFont person:(Person *)pPerson{
    NSArray * actes = [[pPerson Consultations] allObjects];
    NSArray * sortedActes = [actes sortedArrayUsingDescriptors:[NSArray arrayWithObjects:
                                                                [[NSSortDescriptor alloc] initWithKey:@"CreationDate" ascending:NO],
                                                                nil]];
    
    for(int i = 0; i<[sortedActes count]; i++)
    {
        Consultation *c = [sortedActes objectAtIndex:i];
        if(c != nil)
        {
            
            NSString * newString = [[c Traitement] stringByReplacingOccurrencesOfString:@"\n" withString:@", "];
            
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\t\t%-15s\n\t\t%@\n\n",
                                                                                                [[c CreationDate] descriptionWithCalendarFormat:@"%d/%m/%Y" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]],
                                                                                                [[c Diagnostic] UTF8String],
                                                                                                newString ]];
            
            [str addAttribute:NSFontAttributeName value:aFont range:NSMakeRange(0, [str length])];
            [aText appendAttributedString:str];
        }
    }

}

- (void)textDidChange:(NSNotification *)aNotification
{
    
    NSTextView *textView = [aNotification object];
    if(textView == nil)
        return;
    
    NSString * value = [textView string];
    if((value == nil)|| ([value length]<=0))
        return;
    
    NSRange range = [textView selectedRange];
    
    [textView setString:[value uppercaseString]];
    [textView setSelectedRange:range];
    
}

- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
{
    NSTableView *tableView = [aNotification object];
    if(tableView == nil)
        return;
    
    [mJumeller setEnabled:([[tableView selectedRowIndexes] count] == 2)];
    [self setObjEnabled:mInformations withState:([[tableView selectedRowIndexes] count] == 1)];
}

-(void) setObjEnabled:(NSObject *)Obj withState:(bool)Enabled
{
    //Universal way to enable/disable a UI object, including NSBox contents
    
    NSControl * C = (NSControl *)Obj;
    
    if([C respondsToSelector:@selector(setEnabled:)])
        [C setEnabled:Enabled];
    
    if([C.className compare:@"NSTextField"] == NSOrderedSame)
    {
        NSTextField * Ct = (NSTextField*)C;
        if(!Enabled)
            [Ct setTextColor:[NSColor disabledControlTextColor]];
        else //Enabled
            [Ct setTextColor:[NSColor controlTextColor]];
    }
    else if([C.className compare:@"NSBox"] == NSOrderedSame)
    {
        NSBox * Cb = (NSBox*)C;
        
        //There is typically just one subview at this level
        for(NSView * Sub in Cb.subviews)
        {
            //Here is where we'll get the actual objects within the NSBox
            for(NSView * SubSub in Sub.subviews)
                [self setObjEnabled:SubSub withState:Enabled];
        }
    }
}


- (IBAction)jumellerAction:sender{
    NSArray* personnes = [[self mPersons] selectedObjects];
    
    if(mJumellageControllerWnd==nil){
        mJumellageControllerWnd = [[JumellageController alloc] init];
    }
    
    [mJumellageControllerWnd jumellerPersonne:[personnes objectAtIndex:0] avec:[personnes objectAtIndex:1]];
    [mJumellageControllerWnd showWindow:nil];

}

@end
